<template>
  <div>
    <el-card shadow="never">
      <el-row>
        <el-col :span="12">
          <header-title title="智慧秤管理"></header-title>
        </el-col>
        <el-col :span="12">
          智慧秤总数量: <span style="padding-left: 15px;color:#64d9d6;font-size: 22px;">{{scaleTotalSum}}</span> 台
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never">
      <el-row :gutter="20">
        <el-col :span="8">
          <card-item title="电子秤在线数量">
            <template slot="number">
              <div class="number">
                <count-up :end-val="modal.balanceOnlineCount"></count-up>
              </div>
            </template>
          </card-item>
        </el-col>
        <el-col :span="8">
          <card-item title="电子秤离线数量">
            <template slot="number">
              <div class="number">
                <count-up :end-val="modal.balanceOfflineCount"></count-up>
              </div>
            </template>
          </card-item>
        </el-col>
        <el-col :span="8"></el-col>
      </el-row>
    </el-card>
    <el-card shadow="never">
      <el-row>
        <el-col :span="21">
          <div>
            序列号/商户名: <el-input v-model="name" placeholder="请输入内容" size="small" style="margin: 0 10px 0 10px;width: 150px;"></el-input>
            是否在线: <el-select v-model="type" placeholder="是否在线" size="small" style="margin: 0 10px 0 10px;width: 175px;">
              <el-option label="全部" value="-1"></el-option>
              <el-option label="离线" value="0"></el-option>
              <el-option label="在线" value="1"></el-option>
            </el-select>
            <!--商户主营:<el-select v-model="businessType" placeholder="请选择商户主营" size="small" style="margin: 0 10px 0 10px;width: 150px;">
              <el-option label="全部" value="-1"></el-option>
              <el-option label="蔬菜" value="0"></el-option>
              <el-option label="猪肉" value="1"></el-option>
              <el-option label="禽类" value="3"></el-option>
              <el-option label="牛羊肉" value="9"></el-option>
              <el-option label="蛋类" value="10"></el-option>
              <el-option label="豆制品" value="11"></el-option>
            </el-select>-->
            <el-button @click="search" class="button" size="small" round icon="el-icon-search" style="margin: 10px 20px;">查询</el-button>
          </div>
        </el-col>
        <el-col :span="3">
          <el-button @click="addScale" class="button" size="small" round>新增电子秤</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never">
      <div>
        <el-table :data="scaleData" v-loading="loading" style="width: 100%">
          <el-table-column prop="businessName" label="商户名称"></el-table-column>
          <el-table-column prop="serialNumber" label="电子秤编号"></el-table-column>
          <el-table-column prop="clazz" label="电子秤型号"></el-table-column>
          <!--<el-table-column prop="status" label="在线状态"></el-table-column>-->
          <el-table-column prop="statusStr" label="状态字符串"></el-table-column>
          <el-table-column prop="lastHeartbeat" label="最后一次登录时间"></el-table-column>
          <el-table-column fixed="right" label="操作">
            <template slot-scope="scope">
              <!-- <el-button @click="setWisdomScale(scope.row)" type="text" style="color:#64d9d6;">智慧秤设置</el-button> -->
              <el-button @click="repairsScale(scope.row)" type="text" style="color:#71dc80;">报修</el-button>
            </template>
          </el-table-column>
          <div slot="empty"><img src="../../../assets/blank_tip_page/blank_tip_page.png" alt=""></div>
        </el-table>
        <el-pagination
          :page-size="scalePage.size"
          :current-page="scalePage.current"
          :total="scaleTotal"
          @current-change="changeScalePage"
          style="margin-top: 15px;"
          background
          layout="prev, pager, next"
        ></el-pagination>
      </div>
    </el-card>
    <!--<el-dialog :visible.sync="scaleDialog" title="智慧秤设置" @close="close">
      <div>
        <el-form :model="modalDialog" label-width="140px">
          <el-form-item label="智慧秤编号：" style="font-weight: bold;">
            <h3>{{modalDialog.serialNumber}}</h3>
          </el-form-item>
          <el-form-item label="商户名称：" style="font-weight: bold;">
            <h3>{{modalDialog.businessName}}</h3>
          </el-form-item>
          <el-form-item label="智能识别：" style="font-weight: bold;">
            <el-switch v-model="modalDialog.intelligentRecognization" @change="changeIntelligent" active-color="#64d9d6" inactive-color="#cccccc"></el-switch>
          </el-form-item>
          <el-form-item label="按键音开关：" style="font-weight: bold;">
            <el-switch v-model="modalDialog.buttonVoice" @change="changeButtonVoice" active-color="#64d9d6" inactive-color="#cccccc"></el-switch>
          </el-form-item>
          <el-form-item label="语音唱收开关：" style="font-weight: bold;">
            <el-switch v-model="modalDialog.voiceSing" @change="changeVoiceSing" active-color="#64d9d6" inactive-color="#cccccc"></el-switch>
          </el-form-item>
          <el-form-item label="图片实时上传：" style="font-weight: bold;">
            <el-switch v-model="modalDialog.uploadState" @change="changeUploadState" active-color="#64d9d6" inactive-color="#cccccc"></el-switch>
          </el-form-item>
          <el-form-item label="是否显示今日统计：" style="font-weight: bold;">
            <el-switch v-model="modalDialog.statisticsShowState" @change="changeStatistics" active-color="#64d9d6" inactive-color="#cccccc"></el-switch>
          </el-form-item>
          <el-form-item label="界面风格：" style="font-weight: bold;">
            <el-switch v-model="modalDialog.setFontDisplay" @change="changeSetFontDisplay" active-color="#64d9d6" inactive-color="#cccccc"></el-switch>
          </el-form-item>
          <el-form-item label="四舍五入(分)：" style="font-weight: bold;">
            <el-switch v-model="modalDialog.setRoundingOff" @change="changeSetRoundingOff" active-color="#64d9d6" inactive-color="#cccccc"></el-switch>
          </el-form-item>
          <el-form-item label="商户经营种类：" style="font-weight: bold;">
            <el-select v-model="modalDialog.businessType" @change="changeBusinessType" placeholder="请选择">
              <el-option v-for="item in businessTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">设置</el-button>
      </div>
    </el-dialog>-->
    <el-dialog :visible.sync="addScaleDialog" title="新增电子秤" @close="close" v-if="addScaleDialog">
      <div>
        <el-form :model="modelAdd" label-width="140px" :rules="rules" ref="modelAdd">
          <el-form-item label="电子秤编号：" prop="serialNumber">
            <el-input v-model="modelAdd.serialNumber"></el-input>
          </el-form-item>
          <el-form-item label="电子秤型号：" prop="clazz">
            <el-input v-model="modelAdd.clazz"></el-input>
          </el-form-item>
          <el-form-item label="供应商名称：" prop="supplierName">
            <el-input v-model="modelAdd.supplierName"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save('modelAdd')">设置</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="repairsScaleDialog" title="电子秤报修" @close="close" v-if="repairsScaleDialog">
      <div>
        <el-form :model="modelRepairsScale" label-width="140px" :rules="rules2" ref="modelRepairsScale">
          <el-form-item label="电子秤编号：" prop="serialNumber">
            <el-input v-model="modelRepairsScale.serialNumber"></el-input>
          </el-form-item>
          <el-form-item label="报修描述：" prop="description">
            <el-input v-model="modelRepairsScale.description"></el-input>
          </el-form-item>
          <el-form-item label="照片：" prop="photos" class="upload-img-form" ref="uploadElement">
            <!--<el-input v-model="modelRepairsScale.photos"></el-input>-->
            <el-upload class="upload-demo" ref="photos" style="display: inline-block;"
                       action="https://upload.qiniup.com"
                       :on-remove='handleRemove'
                       :on-success="handleSuccessphotos"
                       :show-file-list="false"
                       :limit='6'
                       :data='uploadToken'
                       :before-upload="beforeUpload" v-model="modelRepairsScale.photos"
            >
              <img v-if="modelRepairsScale.photos" :src="modelRepairsScale.photos" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="repairs('modelRepairsScale')">报修</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import HeaderTitle from "@/components/HeaderTitle"
import CountUp from '@/components/CountUp/index'
import CardItem from '@/components/CardItem/index.vue'
import { mapGetters, mapState } from "vuex"
import ElCol from "element-ui/packages/col/src/col";
export default {
  name: 'Equipment',
  components: {
    ElCol,
    HeaderTitle,
     CountUp,
     CardItem
  },
  data(){
    let photos = (rule, value, callback) => {
       console.log(value)
       console.log(this.modelRepairsScale.photos)
      if (value =='') {
        
        callback(new Error("请上传图片"));
      } else {
        callback();
      }
    };
    return {
      uploadToken:{
        key: '',
        token: ''
      },
      // 报修
      repairsScaleDialog: false,
      modelRepairsScale:{
        serialNumber: '', //	string	true	电子秤编号
        description: '', //	string	true	报修描述
        photos: '', //	array	false	照片
      },
      // 新增
      addScaleDialog: false,
      modelAdd:{
        serialNumber: '', //	string	true	电子秤编号
        clazz: '', //	string	true	电子秤型号
        supplierName: '', //	string	true	供应商名称
      },
      loading: true,
      name: '', // 商户名称、电子秤编号
      type: '0', //	int	true	在线状态：0全部，1在线，2离线
      businessType: '-1', //	int	true	商户经营类型	-1 全部 商户主营

      scalePage:{
        current: 1,
        size: 10
      },
      modal: {
        balanceOfflineCount: 0, //	int	电子秤离线数量
        balanceOnlineCount: 0, //	int	电子秤在线数量
      },
      scaleDialog: false,
      modalDialog: {
        serialId: 0,
        serialNumber: '',
        businessName: '',
        intelligentRecognization: false,
        buttonVoice: false,
        voiceSing: false,
        uploadState: false,
        statisticsShowState: false,
        setFontDisplay: false,
        setRoundingOff: false,
        businessType: '0'
      },
      businessTypeList: [],
      rules: {
        serialNumber: [
          { required: true, message: "请输入电子秤编号", trigger: "change" },
        ],
        clazz: [
          { required: true, message: "请输入电子秤型号", trigger: "change" },
        ],
        supplierName: [
          { required: true, message: "请输入供应商名称", trigger: "change" },
        ]
      },
       rules2: {
        description: [
          { required: true, message: "请输入报修描述", trigger: "change" },
        ],
        // photos: [
        //   { required: true, message: "请输入图片", trigger: "change" },
        // ]
        //  photos: [
        //   { required: true, validator: photos, trigger: ["change"] }
        // ],
         photos: [
     { required: true, message: '请上传图片' , trigger: "change"}
    ],
      }
    }
  },
  watch: {
    '$store.state.app.marketId'(val, oldVal){
      if (val != oldVal && oldVal > 0){
        this.getEquipmentData()
        this.goodsToken()
        this.getWisdomScaleList(this.name, parseInt(this.type), this.scalePage.size, this.scalePage.current)
      }
    }
  },
  mounted(){
    this.getEquipmentData()
    this.goodsToken()
    this.getWisdomScaleList(this.name, parseInt(this.type), this.scalePage.size, this.scalePage.current)
  },
  computed: {
    ...mapState("equipment", ["scaleData", "scaleTotal", "scaleTotalSum"]),
    ...mapGetters("equipment", ["filterScaleData"])
  },
  methods:{
    getEquipmentData(){
      this.$store.dispatch('equipment/fetchEquipmentData').then(
        data => {
          this.modal = data
        }
      ).catch(err => {})
    },
    getWisdomScaleList(search, type, perPage, page){
      this.$store.dispatch("equipment/fetchWisdomScaleData", {search, type, perPage, page}).then(
        res => {
          this.loading = false
        }
      )
    },
    search(){
      this.scalePage.current = 1
      this.getWisdomScaleList(this.name, parseInt(this.type), this.scalePage.size, this.scalePage.current)
    },
    changeScalePage(num){
      this.scalePage.current = num
      this.getWisdomScaleList(this.name, parseInt(this.type), this.scalePage.size, num)
    },
    // 点击 智慧秤设置
    setWisdomScale(row){
      console.log(row)
      return
      this.scaleDialog = true
      this.modalDialog.serialId = row.serialId
      this.$store.dispatch('equipment/fetchBusinessType').then(
        data => {
          let items = []
          for (let item of data) {
            items.push({
              value: item.id + '',
              label: item.name
            })
          }
          this.businessTypeList = items
        }
      ).catch(err => {
        this.businessTypeList = []
      })
      this.$store.dispatch('equipment/fetchScaleShow',{serialId: this.modalDialog.serialId}).then(
        data => {
          this.modalDialog = data
          this.modalDialog.businessType = data.businessType + ''
          this.modalDialog.serialId = row.serialId
        }
      )
    },
    // 监听 开关状态
    changeIntelligent(status){
      this.modalDialog.intelligentRecognization = status
    },
    changeButtonVoice(status){
      this.modalDialog.buttonVoice = status
    },
    changeVoiceSing(status){
      this.modalDialog.voiceSing = status
    },
    changeUploadState(status){
      this.modalDialog.uploadState = status
    },
    changeStatistics(status){
      this.modalDialog.statisticsShowState = status
    },
    changeSetFontDisplay(status){
      this.modalDialog.setFontDisplay = status
    },
    changeSetRoundingOff(status){
      this.modalDialog.setRoundingOff = status
    },
    changeBusinessType(type){
      this.modalDialog.businessType = type
    },
    // 提交 设置
    submit(){
      this.scaleDialog = false
      this.$store.dispatch('equipment/fetchScaleEdit', this.modalDialog).then(
        data => {
          this.$message({
            type: 'success',
            message: '设置成功!'
          })
        }
      ).catch(err=>{
        this.$message({
          type: 'error',
          message: '设置失败!'
        })
      })
      this.clear()
    },
    close(){
      this.clear()
    },
    clear(){
      this.modalDialog = {}
      this.modelAdd = {}
    },
    addScale(){
      this.addScaleDialog = true
    },
    // 保存 新增电子秤
    save(modelAdd){
      this.$refs["modelAdd"].validate(valid => {
          if (valid) {
      this.$store.dispatch("equipment/fetchSaveScale", this.modelAdd).then(data => {
        this.addScaleDialog = false
        if(data){
          this.$message({
            type: 'success',
            message: '新增成功，请刷新！'
          })
        }
        this.getWisdomScaleList(this.name, parseInt(this.type), this.scalePage.size, this.scalePage.current)
        this.clear()
      })
        } else {
            this.$message({
              type: "error",
              message: "有必填项未填"
            });
          }
        });
    },
    // 点击报修
    repairsScale(row){
      this.repairsScaleDialog = true
      this.modelRepairsScale.serialNumber = row.serialNumber
    },
    // 去报修
    repairs(modelRepairsScale){
        this.$refs["modelRepairsScale"].validate(valid => {
          if (valid) {
      this.$store.dispatch("equipment/fetchRepairsScale", this.modelRepairsScale).then(data => {
        this.repairsScaleDialog = false
        if(data){
          this.$message({
            type: 'success',
            message: '报修成功，请刷新！'
          })
        }
        this.getWisdomScaleList(this.name, parseInt(this.type), this.scalePage.size, this.scalePage.current)
        this.clear()
      })
      
        } else {
            this.$message({
              type: "error",
              message: "有必填项未填"
            });
          }
        });
    },

    handleSuccessphotos(res, file, fileList){
    this.$refs.uploadElement.clearValidate();
      this.modelRepairsScale.photos = 'http://cailanzi.image.cailanzi001.com/' + res.key
      this.$refs.photos.clearFiles() 
      
    },
    handleRemove(file, fileList) {
      console.log(file,fileList[0])
    },
    beforeUpload(file){
      const isPNG = file.type === "image/png"
      const isJPEG = file.type === "image/jpeg"
      const isJPG = file.type === "image/jpg"
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG && !isJPEG && !isJPG) {
        this.$message.error("上传头像图片只能是 jpg、png、jpeg 格式!")
        return false
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!")
        return false
      }
      //将上传的文件名保存成key,把这个key拼接到外链地址
      const date = new Date()
      this.uploadToken.key=`bill${date.getFullYear()}${date.getMonth()+1}${date.getDate()}${date.getHours()}${date.getMinutes()}${date.getSeconds()}${Math.floor(Math.random()*100)}.${file.type.split('/')[1]}`
    },
    //获取上传文件时候的token
    goodsToken(){
      this.$store.dispatch('purchaseInfo/uptoken',{}).then(
        data => {
          this.uploadToken.token = data.data.uptoken
        }
      ).catch(err => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  /deep/ .el-table__empty-text{
    width: 100%;
  }
.button {
  background: #64d9d6;
  color: #fff;
  margin-left: 40px;
}
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
